package dao

import (
	"context"
	"errors"
	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
	"time"
)

var (
	ErrUserDuplicateEmail = errors.New("邮箱冲突")
	ErrUserNotFount       = gorm.ErrRecordNotFound
)

type UserDAO struct {
	db *gorm.DB
}

func NewUserDap(db *gorm.DB) *UserDAO {
	return &UserDAO{
		db: db,
	}
}

func (dao *UserDAO) FindByEmail(ctx context.Context, email string) (User, error) {
	var u User
	err := dao.db.WithContext(ctx).Where("email = ?", email).First(&u).Error
	//err := dao.db.WithContext(ctx).First(&u, "email = ?", email).Error
	return u, err
}

func (dao *UserDAO) Insert(ctx context.Context, u User) error {
	now := time.Now().UnixMilli()
	u.Ctime = now
	u.Utime = now
	err := dao.db.WithContext(ctx).Create(&u).Error
	if mysqlErr, ok := err.(*mysql.MySQLError); ok {
		const uniqueConflictsErrNo uint16 = 1062
		if mysqlErr.Number == 1062 {
			// 邮箱冲突
			return ErrUserDuplicateEmail
		}
	}
	return err
}

func (dao *UserDAO) FindById(ctx context.Context, userId int64) (User, error) {
	var u User
	dao.db.WithContext(ctx).Where("id = ?", userId).First(&u)
	return u, nil
}

func (dao *UserDAO) UpdateById(ctx context.Context, user User) error {
	err := dao.db.WithContext(ctx).Model(&user).Updates(User{Nickname: user.Nickname, Birthday: user.Birthday, AboutMe: user.AboutMe}).Error
	return err
}

// User 直接对应数据库表
type User struct {
	Id       int64  `gorm:"autoIncrement,primaryKey"`
	Email    string `gorm:"unique"`
	Password string
	Nickname string
	AboutMe  string
	Birthday string

	// 毫秒
	Ctime int64
	Utime int64
}
